package com.sunmi.paymentdemo.activity;

import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.google.gson.Gson;
import com.sunmi.payment.PaymentService;
import com.sunmi.paymentdemo.bean.Request;
import com.sunmi.paymentdemo.dialog.WaitingDialog;
import com.sunmi.paymentdemo.receiver.ResultReceiver;

/**
 * Created by yiuhet on 2019/7/2.
 * <p>
 * 调用L3的基类Activity
 */
public abstract class BaseActivity extends AppCompatActivity implements View.OnClickListener {

    protected WaitingDialog mLoadingDialog; //loading框
    private ResultReceiver mResultReceiver; //结果广播接收器
    private Gson gson = new Gson();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mLoadingDialog = new WaitingDialog(this);
        mLoadingDialog.setCancelBtnShow(false);
        registerResultReceiver();
    }

    /**
     * 调用收银台
     *
     * @param request
     */
    protected void callPayment(String request) {
        Log.i("yiuhet", "callPayment：" + request);
        PaymentService.getInstance().callPayment(request, new PaymentService.PaymentCallback() {
            @Override
            public void callFail() {
                Log.e("yiuhet", "callFail");
                mLoadingDialog.dismiss();
                Toast.makeText(BaseActivity.this, "调用失败,请重试！", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void callSuccess() {
                Log.i("yiuhet", "callSuccess");
            }
        });
        mLoadingDialog.show();
    }

    /**
     * 请求参数转换成转字符串
     *
     * @param request
     * @return
     */
    protected String reqConvertString(Request request) {
        return gson.toJson(request);
    }

    /**
     * 注册结果接收广播
     */
    protected void registerResultReceiver() {
        mResultReceiver = new ResultReceiver(result -> {
            if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
                mLoadingDialog.dismiss();
            }
            Log.i("yiuhet", "receive:" + result);
            onReceive(result);
        });
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ResultReceiver.RESPONSE_ACTION);
        registerReceiver(mResultReceiver, intentFilter);
    }

    /**
     * 生成请求参数
     *
     * @return
     */
    protected abstract Request convertRequest();

    /**
     * 接收到结果后给子类处理
     *
     * @param result
     */
    protected abstract void onReceive(String result);

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mResultReceiver != null) {
            unregisterReceiver(mResultReceiver);
        }
    }
}
